package com.chhuang.tutool.ui.fragment

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chhuang.tutool.R
import com.chhuang.tutool.adapter.ChannelFlowAdapter
import com.chhuang.tutool.adapter.MessageListAdapter
import com.chhuang.tutool.databinding.FragmentTcpServerBinding
import com.chhuang.tutool.modle.MessageBean
import com.chhuang.tutool.socket.NettyServer
import com.gnetek.tool.base.BaseFragment
import com.swallowsonny.convertextlibrary.hex2ByteArray
import com.swallowsonny.convertextlibrary.toHexString
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.net.InetSocketAddress

class TCPServerFragment(private val port:Int): BaseFragment() {
    companion object {
        private const val TAG = "TCPServerFragment"
    }

    private lateinit var binding: FragmentTcpServerBinding
    //列表适配器
    private val messageListAdapter = MessageListAdapter(mutableListOf())
    private lateinit var tagAdapter: ChannelFlowAdapter

    private var tcpServer: NettyServer? = null

    private var ipPorts = mutableListOf<String>()
    private var sessionIds = mutableListOf<String>()

    override fun bindView(inflater: LayoutInflater, container: ViewGroup?): View {
        binding = FragmentTcpServerBinding.inflate(inflater, container, false)
        val view: View = binding.root
        return view
    }

    override fun initView() {
        //客户端
        tagAdapter = ChannelFlowAdapter(requireContext())
        binding.bottomFlowTaglayout.adapter = tagAdapter
        binding.bottomFlowTaglayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_MULTI)//多选
        //监听选择tag事件
//        binding.bottomFlowTaglayout.setOnTagSelectListener { parent: FlowTagLayout?, position: Int, selectedList: List<Int?>? ->}
        tagAdapter.addTags(ipPorts.toList())
//        tagAdapter.setSelectedPositions(2, 3, 4)//设置选中
//        tagAdapter.selectedIndexs//获取选中的tags

        //消息
        WidgetUtils.initRecyclerView(binding.messageRecyclerView)
        binding.messageRecyclerView.adapter = messageListAdapter
    }

    override fun initData() {
        doAsync {
            NettyServer(port, {
                tcpServer = it
                uiThread {
                    xToasts("server run success",1)
                }
            },{
                uiThread {
                    xToasts("server run error",0)
                }
            },{ it, ip, port->
                //收到的消息 it 获取
                val datas = it
                uiThread {
                    val message = if(binding.hexSwitchButton.isChecked){
                        datas.toHexString()
                    }else {
//                        datas.readStringBE(0, datas.size,"ascii")
                        String(datas, Charsets.UTF_8)
//                        String(datas, Charset.forName("GBK"))
                    }
                    Log.e(TAG, "initData: ${message}" )
                    val messageBean = MessageBean(ip, port, message,false)
                    messageListAdapter.loadOne(messageBean)
                }
            },{
                sessionIds.clear()
                ipPorts.clear()
                for ((key, value) in it){
                    sessionIds.add(key)
                    val remote = value.remoteAddress() as InetSocketAddress
                    val ip = remote.address.hostAddress
                    val rport = remote.port
                    ipPorts.add("${ip}:${rport}")
                }
                uiThread {
//                    tagAdapter.clearAndAddTags(ipPorts.toList())//这个删除空的时候有问题
                    tagAdapter.clearData()
                    tagAdapter.addTags(ipPorts.toList())
                }
            })
        }
    }

    override fun initListener() {
        binding.sendButton.setOnClickListener {
            val selectIds = mutableListOf<String>()//选中的session，用于发送消息
            for (index in tagAdapter.selectedIndexs){
                selectIds.add(sessionIds[index])
            }
            //发送消息
            val content = binding.contentEditText.text
            if(content.isNotBlank() && selectIds.isNotEmpty()) {
                val message = content.toString()
                Log.e(TAG, "initListener: ${message}")
                val data = if(binding.hexSwitchButton.isChecked){
                    message.hex2ByteArray()
                }else {
//                    message.ascii2ByteArray()
                    message.toByteArray(Charsets.UTF_8)
//                    message.toByteArray(Charset.forName("GBK"))
                }
                tcpServer?.let {
                    it.sendMessage(data, selectIds)
                    val local = it.getLocalSocketAddress()
                    val messageBean = if(local!=null){
                        MessageBean(if(local.address.hostAddress==null)"local sender" else local.address.hostAddress,
                            local.port,
                            message)
                    }else {
                        MessageBean("local sender", port, message)
                    }
                    messageListAdapter.loadOne(messageBean)
                    xToasts(R.string.send_success, 1)
                    binding.contentEditText.text = null
                }
            }
        }
    }

    override fun onDestroy() {
        tcpServer?.destory()
        super.onDestroy()
    }

}